<template>
  <div>
    <!-- 新增 -->
    <el-dialog
      append-to-body
      title="新增"
      :visible.sync="data.dialogInfoFlag"
      width="680px"
      @close="handleClose"
      @opened="openDialog"
    >
      <el-form :model="data.form" label-width="100px" ref="addForm" :rules="data.rules">
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="data.form.username" placeholder="请输入用户名（邮箱）"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input type="password" v-model="data.form.password" placeholder="请输入6~20位数字+字母"></el-input>
        </el-form-item>
        <el-form-item label="姓名：" prop="truename">
          <el-input v-model="data.form.truename" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone">
          <el-input v-model.number="data.form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="地区：">
          <cityPicker
            :cityPickerLevel="['province', 'city', 'area', 'street']"
            :cityPickerData.sync="data.cityPickerData"
          />
        </el-form-item>
        <el-form-item label="是否启用：" prop="status">
          <el-radio v-model="data.form.status" label="1">禁用</el-radio>
          <el-radio v-model="data.form.status" label="2">启用</el-radio>
        </el-form-item>
        <el-form-item label="角色：" prop="role">
          <el-checkbox-group v-model="data.form.role">
            <el-checkbox
              v-for="item in data.roleData"
              :key="item.id"
              :label="item.role"
            >{{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="按钮权限：">
          <template v-if="data.btnPermData.length > 0">
            <div v-for="item in data.btnPermData">
              <h4>{{ item.name }}</h4>
              <template v-if="item.perm && item.perm.length > 0">
                <el-checkbox-group v-model="data.form.btnPerm">
                  <el-checkbox
                    v-for="buttons in item.perm"
                    :key="buttons.value"
                    :label="buttons.value"
                  >{{ buttons.name }}
                  </el-checkbox>
                </el-checkbox-group>
              </template>
            </div>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="subForm('addForm')"
          :loading="data.subLoading"
        >确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import sha1 from "js-sha1";
import { GetRole, GetSystem, GetPermButton, AddUser, EditUser } from "@/api/user";
import cityPicker from "@c/cityPicker";
import { reactive, onBeforeMount, watchEffect } from "@vue/composition-api";
import { stripscript, validateEmail, validatePass } from "@/utils/validate";

export default {
  name: "Info",
  components: {
    cityPicker
  },
  // 单向数据流 父级 ==> 子级 不能反向修改
  props: {
    flag: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: () => {
      }
    }
  },
  setup(props, { emit, root, refs }) {
    // 验证邮箱
    let validateUserName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (validateEmail(value)) {
        callback(new Error("用户名格式有误"));
      } else {
        callback();
      }
    };
    // 验证密码
    let validatePassword = (rule, value, callback) => {
      /**
       * 业务逻辑
       * 1. 编辑状态
       *    需要检验：data.form.id 存在并且， 密码不为空时
       *    不需要检验：data.form.id 存在并且，密码为空时
       * 2. 添加状态
       *    需要检验：data.form.id 不存在
       */
      if (data.form.id && !value) {
        callback();
      }
      if ((data.form.id && value) || !data.form.id) {
        if (value) {
          data.form.password = stripscript(value);
          value = data.form.password;
        }
        if (value === "") {
          callback(new Error("请输入密码"));
        } else if (validatePass(value)) {
          callback(new Error("密码为6至20位数字＋字母"));
        } else {
          callback();
        }
      }
    };
    /**
     * 数据
     */
    const data = reactive({
      dialogInfoFlag: false,  // 弹窗标记
      cityPickerData: {},
      form: {
        username: "",
        truename: "",
        password: "",
        phone: "",
        region: {},
        status: "2",
        role: [],
        btnPerm: []
      },
      rules: {
        username: [
          { validator: validateUserName, trigger: "blur" }
        ],
        password: [
          { validator: validatePassword, trigger: "blur" }
        ],
        role: [
          { required: true, message: "请选择角色", trigger: "change" }
        ]
      },
      // 角色选择
      roleData: [],
      // 按钮权限
      btnPermData: [],
      // 按钮加载
      subLoading: false
    });

    /**
     * methods
     */
      // 关闭弹窗的回调
    const handleClose = () => {
        data.dialogInfoFlag = false;
        emit("update:flag", false);
        restForm();
      };
    // 打开弹窗的回调
    const openDialog = () => {
      // 获取角色
      getRole();
      let editData = props.editData;
      // 初始值处理
      if (editData.id) { // 编辑
        editData.role = editData.role ? editData.role.split(",") : [];
        editData.btnPerm = editData.btnPerm ? editData.btnPerm.split(",") : [];
        // 循环json对象
        for (let key in editData) {
          data.form[key] = editData[key];
        }
      } else { // 添加
        data.form.id && delete data.form.id;
      }
    };

    const subForm = (formName) => {
      data.subLoading = true;
      refs[formName].validate((valid) => {
        if (valid) {
          // 参数
          let requestData = Object.assign({}, data.form);
          requestData.role = data.form.role.join(); // 数组转字符串，默认以用逗号隔开
          requestData.btnPerm = data.form.btnPerm.join(); // 数组转字符串，默认以用逗号隔开
          requestData.region = JSON.stringify(data.cityPickerData);
          // 添加状态： 需要密码，并且加密码
          // 编辑状态： 值存在，需要密码，并且加密码，否则删除
          if (requestData.id) {
            if (requestData["password"]) {
              requestData["password"] = sha1(requestData.password);
            } else {
              delete requestData["password"];
            }
            editUser(requestData);
          } else {
            requestData["password"] = sha1(requestData.password);
            addUser(requestData);
          }
        } else {
          data.subLoading = false;
        }
      });
      /*
      深拷贝：JSON.parse(JSON.stringify(data.form)) // 字符串 再次转json对象
      注意事项：丢失 方法 / undefined Symbol() 三种类型
      例子：let test = {
              aa: function () {},
              bb: undefined,
              cc: Symbol(),
              dd: "dd",
              ee: {name: "ee", age: "20"},
              ff: ["ff", "20"],
              xx: 20,
              hh: false
           };
      console.log(JSON.parse(JSON.stringify(test)));

      结果： dd: "dd"
            ee: {name: "ee", age: "20"}
            ff: (2) ["ff", "20"]
            xx: 20
            hh: false
       */

      // 浅拷贝：Object.assign({}, data.form); // 拷贝出来的就是一个对象
    };
    // 添加用户
    const addUser = (requestData) => {
      AddUser(requestData).then(res => {
        let resData = res.data;
        if (resData.resCode === 0) {
          root.$message.success(resData.message);
        }
        data.subLoading = false;
        restForm();
        // 调用父组件的方法
        emit("loadData");
      }).catch(error => {
        console.log(error);
        data.subLoading = false;
      });
    };
    // 编辑用户
    const editUser = (requestData) => {
      EditUser(requestData).then(res => {
        let resData = res.data;
        if (resData.resCode === 0) {
          root.$message.success(resData.message);
        }
        data.subLoading = false;
        restForm();
        // 调用父组件的方法
        emit("loadData");
      }).catch(error => {
        console.log(error);
        data.subLoading = false;
      });
    };

    // 清空表单
    const restForm = () => {
      refs["addForm"].resetFields();
      emit("update:flag", false);

      console.log('cityPickerData');
      console.log(data.cityPickerData);
      data.cityPickerData = {};
      data.form.role = [];
    };

    // 获取角色
    const getRole = () => {
      if (data.roleData.length === 0) {
        GetRole().then(res => {
          data.roleData = res.data.data;
        }).catch(error => {
          console.log(error);
        });
      }
      if (data.btnPermData.length === 0) {
        GetPermButton().then(res => {
          data.btnPermData = res.data.data;
        }).catch(error => {
          console.log(error);
        });
      }
    };

    /**
     * watch
     */
    watchEffect(() => data.dialogInfoFlag = props.flag);

    /**
     * 生命周期
     */
    onBeforeMount(() => {});

    return {
      // reactive
      data,
      // methods
      handleClose, openDialog, subForm
    };
  }
};
</script>

<style lang="scss" scoped></style>
